package net.zjitc.bookshop15.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.zjitc.bookshop15.pojo.User;
import net.zjitc.bookshop15.pojo.loginUser;
import net.zjitc.bookshop15.service.userService;
import net.zjitc.bookshop15.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author 董熠涛
 * @date 2025/4/28 14:33
 */
@Service
@Slf4j
public class userServiceImpl implements userService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String login(User user) throws JsonProcessingException {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (authenticate == null) {
            return "登录失败";
        }

        ObjectMapper objectMapper = new ObjectMapper();
        loginUser loginuser = (loginUser) authenticate.getPrincipal();
        log.info("loginuser = " + loginuser);
        String s = objectMapper.writeValueAsString(loginuser);
        String jwt = JwtUtils.generateToken(s, 1000L * 60 * 60);

        stringRedisTemplate.opsForValue().set("token_"+jwt,jwt, 60 * 60, TimeUnit.SECONDS);
        return jwt;
    }
}
